/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL
v2. You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai.wyl on 2021/5/18.
//

#include "storage/index/index_meta.h"

#include "common/lang/string.h"
#include "common/log/log.h"
#include "json/json.h"
#include "storage/field/field_meta.h"
#include "storage/table/table_meta.h"

static const Json::StaticString IS_UNIQUE("is_unique");
static const Json::StaticString FIELD_NAME("name");
static const Json::StaticString FIELD_FIELD_NAMES("field_names");
static const Json::StaticString NAME("name");

RC IndexMeta::init(bool is_unique, const char *name,
                   const std::vector<FieldMeta> &fields) {
  if (common::is_blank(name)) {
    LOG_ERROR("Failed to init index, name is empty.");
    return RC::INVALID_ARGUMENT;
  }
  is_unique_ = is_unique;
  name_ = name;
  for (const FieldMeta &fieldMeta : fields) {
    fields_.emplace_back(fieldMeta.name());
  }
  //  field_ = field.name();
  return RC::SUCCESS;
}

void IndexMeta::to_json(Json::Value &json_value) const {
  json_value[IS_UNIQUE] = is_unique_;
  json_value[FIELD_NAME] = name_;
  int num = field_num();
  Json::Value field_filed_names;
  //  std::string res;
  for (int i = 0; i < num; i++) {
    Json::Value json;
    json[NAME] = std::string(field(i));
    field_filed_names.append(std::move(json));
  }
  json_value[FIELD_FIELD_NAMES] = field_filed_names;
}

RC IndexMeta::from_json(const TableMeta &table, const Json::Value &json_value,
                        IndexMeta &index) {
  const Json::Value &is_unique_value = json_value[IS_UNIQUE];
  const Json::Value &name_value = json_value[FIELD_NAME];
  const Json::Value &field_value_names = json_value[FIELD_FIELD_NAMES];
  if (!is_unique_value.isBool()) {
    LOG_ERROR("Invalid is_unique arg, json value=%s",
              is_unique_value.toStyledString().c_str());
    return RC::INTERNAL;
  }
  if (!name_value.isString()) {
    LOG_ERROR("Index name is not a string. json value=%s",
              name_value.toStyledString().c_str());
    return RC::INTERNAL;
  }

  if (!field_value_names.isArray() || field_value_names.size() < 0) {
    LOG_ERROR("Invalid table meta. fields is not array, json value=%s",
              field_value_names.toStyledString().c_str());
    return RC::SCHEMA_FIELD_MISSING;
  }
  //  if (!field_value_names.isString()) {
  //    LOG_ERROR("Field name of index [%s] is not a string. json value=%s",
  //        name_value.asCString(),
  //        field_value.toStyledString().c_str());
  //    return RC::INTERNAL;
  //  }

  //  const FieldMeta *field = table.field(field_value.asCString());
  //  if (nullptr == field) {
  //    LOG_ERROR("Deserialize index [%s]: no such field: %s",
  //    name_value.asCString(), field_value.asCString()); return
  //    RC::SCHEMA_FIELD_MISSING;
  //  }

  // 解析json
  std::vector<FieldMeta> fields;
  int num = field_value_names.size();
  for (int i = 0; i < num; i++) {
    const Json::Value &value_name = field_value_names[i];
    const Json::Value &name = value_name[NAME];
    if (!name.isString()) {
      LOG_ERROR("Failed to deserialize index field. field name =%s",
                name.toStyledString().c_str());
      return RC::GENERIC_ERR;
    }
    const char *field_name = name.asCString();
    const FieldMeta *field_meta = table.field(field_name);
    if (nullptr == field_meta) {
      return RC::SCHEMA_FIELD_MISSING;
    }
    fields.emplace_back(*field_meta);
  }

  return index.init(is_unique_value.asBool(), name_value.asCString(), fields);
}

const char *IndexMeta::name() const { return name_.c_str(); }

const char *IndexMeta::field(int idx) const {
  //  return field_.c_str();
  return fields_.at(idx).c_str();
}

std::string IndexMeta::fields() const {
  std::string str;
  for (int i = 0; i < fields_.size(); i++) {
    if (i != 0) {
      str += ", ";
    }
    str += fields_.at(i);
  }
  return str;
}

void IndexMeta::desc(std::ostream &os) const {
  os << "index name=" << name_ << ", fields=";
  for (int i = 0; i < fields_.size(); i++) {
    if (i != 0) {
      os << ", ";
    }
    os << fields_.at(i);
  }
}
